package com.btkjgc.controller;

import com.btkjgc.models.LeftMenu;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

/**
 * Created by _ESE on 2015/2/2.
 */
public class BaseController
{
	Logger logger = Logger.getLogger(BaseController.class);

	public LeftMenu getMenu(List<LeftMenu> sidebarlist, String uri)
	{
		if (sidebarlist != null)
		{
			for (LeftMenu l1 : sidebarlist)
			{
				if (l1.getUrl() != null && l1.getUrl().equals(uri)) { return l1; }
				for (LeftMenu l2 : l1.getSubmenus())
				{
					if (l2.getUrl() != null && l2.getUrl().equals(uri)) { return l2; }
					for (LeftMenu l3 : l2.getSubmenus())
					{
						if (l3.getUrl() != null && l3.getUrl().equals(uri)) { return l3; }
					}
				}
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	public ModelAndView LeftBar(ModelAndView mv, HttpServletRequest request)
	{
		if (mv == null) { return null; }
		List<LeftMenu> sidebarlist = (List<LeftMenu>) request.getSession()
				.getAttribute("left_menu");

		if (sidebarlist != null)
		{
			String uri = request.getRequestURI();
			LeftMenu current = getMenu(sidebarlist, uri);
			if (current != null && current.getUrl() != null)
			{
				uri = current.getNav_url();
			}

			boolean active = false;
			for (LeftMenu l1 : sidebarlist)
			{
				l1.setActive(false);
				if (l1.getNav_url() != null && l1.getNav_url().equals(uri))
				{
					active = true;
					l1.setActive(true);
				}
				for (LeftMenu l2 : l1.getSubmenus())
				{
					l2.setActive(false);
					if (l2.getNav_url() != null && l2.getNav_url().equals(uri))
					{
						active = true;
						l1.setActive(true);
						l2.setActive(true);
					}
					for (LeftMenu l3 : l2.getSubmenus())
					{
						l3.setActive(false);
						if (l3.getNav_url() != null
								&& l3.getNav_url().equals(uri))
						{
							active = true;
							l1.setActive(true);
							l2.setActive(true);
							l3.setActive(true);
						}
					}
				}
			}
			if (!active)
			{
				sidebarlist.get(0).setActive(true);
			}
			mv.addObject("sidebarlist", sidebarlist);
		}

		return mv;
	}
}
